package org.kc4.sso.listener;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.kc4.sso.auth.SSOContextParameters;
import org.kc4.sso.crypto.SSOAsymmetricCipher;

/**
 * Application Lifecycle Listener implementation class SSOClientListener
 *
 */
public class SSOClientListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent event) {
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {

		HttpSession session = event.getSession();
		ServletContext context = session.getServletContext();

		// コンテキストパラメーターのロード
		SSOContextParameters.getInstance(context);

		if (SSOContextParameters.getInstance().getProviderURL() == null ||
			SSOContextParameters.getInstance().getProviderURL().isEmpty()) {

			throw new IllegalStateException("SSO-Client is required context-param, \"ProviderURL\" setting.");
		}

		try {

			String authorizationToken = (String) session.getAttribute(
				SSOContextParameters.getInstance().getNamingOfAuthorizationToken());
			SSOAsymmetricCipher cipher = (SSOAsymmetricCipher) session.getAttribute(
				SSOContextParameters.getInstance().getNamingOfAsymmetricCipher());

			String contextUrl = InetAddress.getLocalHost().getHostName() + context.getContextPath();

			// 接続クライアント生成
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
				SSOContextParameters.getInstance().getProxy());
			HttpPost post = new HttpPost(SSOContextParameters.getInstance().getProviderURL());

			// 送信パラメタ生成
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair(SSOContextParameters.getInstance()
				.getNamingOfAuthorizationToken(), authorizationToken));
			pairs.add(new BasicNameValuePair(SSOContextParameters.getInstance()
					.getNamingOfContextUrl(), contextUrl));
			pairs.add(new BasicNameValuePair(SSOContextParameters.getInstance()
				.getNamingOfSignoffSignature(), cipher.signAsHex(authorizationToken)));
			post.setEntity(new UrlEncodedFormEntity(pairs));

			client.execute(post);
			//HttpResponse res = client.execute(post);
		}
		catch (IOException e) {

			throw new IllegalStateException(e);
		}

	}
}
